﻿using System;
using System.Web.Mvc;
using NHibernate;

namespace Xango.Data.NHibernate.Filters
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class NeedsPersistenceAttribute
        : NHibernateSessionAttribute
    {
        protected ISession session
        {
            get { return sessionFactory.GetCurrentSession(); }
        }

        public override void OnActionExecuting(
            ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            session.BeginTransaction();
        }

        public override void OnActionExecuted(
            ActionExecutedContext filterContext)
        {
            ITransaction tx = session.Transaction;
            
            if (tx != null && tx.IsActive)
            {
                try { session.Transaction.Commit(); }
                catch (Exception)
                {
                    session.Transaction.Rollback();
                    throw;
                }
            }

            base.OnActionExecuted(filterContext);
        }
    }
}